<!--
 * @Description: 主页面
 * @Author: fxg
 * @Date: 2020-06-29 11:18:28
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-03-25 09:58:37
-->
<template>
  <div class="home">
    <el-container>
      <el-header>
        <div class="top">
          <top-nav />
        </div>
      </el-header>
      <el-main class="home_content">
        <div class="tags">
          <el-tabs v-if="!show" v-model="actibeIndex" type="card" @tab-remove="removeTab" @tab-click="handleClick">
            <el-tab-pane name="index">
              <span slot="label">
                首页
                <i class="nav_home_I el-icon-s-home" />
              </span>
            </el-tab-pane>
            <el-tab-pane v-for="(item, index) in navList" :key="index + item.name" lazy :name="item.name" closable>
              <span slot="label" @contextmenu.prevent="contextMenu($event,item.name)"> {{item.meta.title}}</span>
            </el-tab-pane>
          </el-tabs>
          <ul v-show="visible" class="contextmenu" :style="{left: contextMenuLeft + 'px', top: contextMenuTop + 'px'}">
            <li @click="close('others')">关闭其他</li>
            <li @click="close('all')">关闭所有</li>
          </ul>
        </div>

        <!-- <router-view :key="key" /> -->
        <keep-alive max="5">
          <transition name="breadcrumb">
            <router-view v-if="!$route.meta.keepAlive" />
          </transition>
        </keep-alive>
        <transition name="breadcrumb">
          <router-view v-if="$route.meta.keepAlive" />
        </transition>
        <!-- show为false时显示 -->
        <div v-if="!show && showLeft" class="left_nav_div">
          <div>
            <leftNav></leftNav>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
/* 引入组件*/
import topNav from "@/components/top_nav";
/* 引入scss里的变量*/
import styles from "@/app.scss";
/* 全局调用*/
import addTab from "@/common/addTab.js";
import leftNav from "@/components/left_nav";
import mixin from "@/mixins/mixin.js";
import { setCurrentTab } from "@/utils/auth";
export default {
  inject: ['reload'],
  mixins: [mixin],
  components: {
    topNav,
    leftNav,
  },
  data() {
    return {
      actibeIndex: "index",
      bg_color: styles.bg_color,
      bg_background1: styles.bg_background1,
      bg_background2: styles.bg_background2,
      navList: [],
      show: true,
      showLeft: true,
      whiteList: ["controlLibrary", "download", "Saleskanban", "userInfo", "details"],
      /**关闭标签*/
      contextMenuLeft: 0,
      contextMenuTop: 0,
      visible: false,
      name: ''
    };
  },
  computed: {
    key() {
      return this.$route.path;
    },
  },
  watch: {
    /* 添加标签
     * @description 监听路由变化。路由变化就开始执行
     * 如路由不在navList列表里，就加入当前路由到navList
     */
    $route: {
      handler: function () {
        this.$nextTick(function () {
          let _this = this;
          _this.actibeIndex = _this.$route.name;
          const { fullPath } = _this.$route;
          /*判断是否是一级页面*/
          if (this.$route.name === "index") {
            this.show = true;
            return;
          }
          this.show = false;
          /*判断是否是二级级页面是否显示左边导航栏*/
          if (
            this.whiteList.indexOf(this.$route.name) !== -1
          ) {
            this.showLeft = false;
          } else {
            this.showLeft = true;
          }
          /**加入标签*/
          if (_this.checkRoute(fullPath)) {
            /**取消三级页面的欢迎页加入标签*/
            if (_this.actibeIndex == 'basicIndex' || _this.actibeIndex == 'ICPSIndex') {
              return
            }
            _this.navList.push(_this.checkRoute(fullPath));
          }
        });
      },
      deep: true,
    },
    navList: {
      handler: function (val) {
        const list = [];
        val.forEach((item) => {
          list.push({
            fullPath: item.fullPath,
            meta: item.meta,
            name: item.name,
            path: item.path,
          });
        });
        sessionStorage.setItem("navList", JSON.stringify(list));
      },
      deep: true,
    },
    visible(value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    }
  },
  /**直接打开连接*/
  created() {
    this.actibeIndex = this.$route.name;
    const { fullPath } = this.$route;
    /*判断是否是一级页面*/
    if (this.$route.name === "index") {
      this.$store.dispatch("ChangeactiveIndex", "");
      this.show = true;
      return;
    }
    this.show = false;
    /*判断是否是二级级页面是否显示左边导航栏*/
    if (
      this.whiteList.indexOf(this.$route.name) !== -1
    ) {
      this.showLeft = false;
    } else {
      this.showLeft = true;
    }
    /**判断当没有页面存在时，加入新页面*/
    if (JSON.parse(sessionStorage.getItem("navList")) == null) {
      if (this.actibeIndex !== 'basicIndex' && this.actibeIndex !== 'ICPSIndex') {
        this.navList.push(this.checkRoute(fullPath));
      }
    } else {
      this.navList = JSON.parse(sessionStorage.getItem("navList"));
    }
    /**查询当前页面属于哪一个页面
    更改储存topnav的选中值*/
    let key = this.$route.meta.system;
    /**非首页时存储最新页面路由信息*/
    this.$store.dispatch("ChangeactiveIndex", key);
    switch (key) {
      /**基础系统*/
      case "organization": {
        this.$store.dispatch("Changeindex", this.$route.name);
        this.$store.dispatch("Changelist", this.basismenu);
        return;
      }
      /**ICPS系统*/
      case "basicSite": {
        this.$store.dispatch("ChangeICPSindex", this.$route.name);
        this.$store.dispatch("Changelist", this.ICPS);
        return;
      }
    }
  },
  mounted() {
    /**
     * @Description  所有的路由跳转，可再次判断流程是否打开新页面或者跳已有页面。
     * @Param
     * @Author wangwangwang
     */
    addTab.$on("name", (name, type, index) => {
      setCurrentTab(name);
      const tabList = JSON.parse(window.sessionStorage.getItem("navList")) || []
      if (type === 1) { // 点击tab进行跳转
        const pathName = tabList[index*1-1]?.fullPath;
        if (pathName) {
          this.$router.push({ path: pathName });
          return
        }
        this.$router.push({ name: 'index' });
      } else { // 点击navitem进行跳转
        const hasIndex = tabList.findIndex(item => item.name === name);
        if (hasIndex !== -1) {
          const { fullPath } = tabList[hasIndex];
          const fullPaths = fullPath.split('?');
          if (fullPaths.length > 1) {
            this.$router.push({ name });
            return
          }
          this.$router.push({ name });
          return
        }
        this.$router.push({ name });
      }
    });
    /**
     * 移除导航栏
    */
    addTab.$on('remove', (name) => {
      this.removeTab(name)
    });

  },
  methods: {
    /**  关闭页面
    */
    close(key) {
      if (key.includes('all')) {
        this.navList = []
        this.$router.push({ name: "index" });
        // 关闭所有，除了home
      } else if (key.includes('others')) {
        // 关闭除当前页和home页的其他页
        const tabs = this.navList;
        this.navList = tabs.filter((tab) => tab.name == this.name);
        if (this.$route.name !== this.name) {
          this.$router.push({ name: this.name });
        }
      }
      this.visible = false
    },
    /**
     * 鼠标右键事件
    */
    contextMenu(e, name) {
      this.visible = true
      this.name = name
      this.contextMenuLeft = e.clientX - this.$el.getBoundingClientRect().left + 10
      this.contextMenuTop = e.clientY - 64
    },
    closeMenu() {
      this.visible = false
    },
    /**  验证标签
     * @description 判断路由是否存在
     * try跳出forEach循环，存在直接抛出错误
     * @param {item} item 指向路由名
     * @return {string} 0代表路由已存在，不存在返回当前路由参数
     */
    checkRoute(fullPath) {
      let route = null;
      try {
        if (this.navList.length !== 0) {
          this.navList.forEach((tab) => {
            if (tab.fullPath === fullPath) {
              route = 0;
              throw Error();
            }
          });
        }
        route = this.$route;
      } catch (e) {
        return;
      }
      return route;
    },
    /* 切换标签
     * @description 切换二级路由
     */
    handleClick(tab) {
      // const { query, name } = this.$route;
      // const newObject = Object.keys(query);
      // /**
      //  * @Description 将query缓存起来
      //  * @Param
      //  * @Author wangwangwang
      //  */
      // if (tab.name == name) {
      //   this.reload();
      //   return
      // }
      // if (newObject.length) {
      //   const queryList = JSON.parse(window.sessionStorage.getItem("queryList")) || [];
      //   let hasKeys = false;
      //   const data = {
      //     name: this.$route.name,
      //     query: this.$route.query,
      //   };
      //   const newArry = queryList.map((item) => {
      //     if (item.name === this.$route.name) {
      //       hasKeys = true;
      //       return data;
      //     }
      //     return item;
      //   });
      //   if (hasKeys) {
      //     window.sessionStorage.setItem("queryList", JSON.stringify(newArry));
      //   } else {
      //     queryList.push(data);
      //     window.sessionStorage.setItem("queryList", JSON.stringify(queryList));
      //   }
      // }
      // const tabList = JSON.parse(window.sessionStorage.getItem("navList"))
      // console.log(tabList)
      // console.log(tab.index)
      addTab.$emit("name", tab.name, 1, tab.index);
    },
    /* 移除标签*/
    removeTab(targetName) {
      const tabs = this.navList;
      if (this.navList.length === 1) {
        this.actibeIndex = "index";
        this.$router.push({ name: "index" });
      }
      let activeName = this.actibeIndex;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
        addTab.$emit("name", activeName);
      }
      this.actibeIndex = activeName;
      setCurrentTab(activeName);
      this.navList = tabs.filter((tab) => tab.name !== targetName);
    },
  },
  beforeDestroy() {
    addTab.$off("name");
    addTab.$off("remove");
  },
};
</script>
<style lang="scss">
// 优化eleUI的样式及动态配置颜色和字体

.home > .el-container > .el-header {
  background: linear-gradient(to right, $bg_background1, $bg_background2);
  > .top {
    padding: 0 $px_24;
    display: flex;
  }
  padding: 0;
}
.home > .el-container > .el-main {
  // min-width: 1366px;
  position: relative;
  padding: 0;
  overflow-x: hidden;
  overflow-y: auto;
}
.el-tabs__nav-next,
.el-tabs__nav-prev {
  position: absolute;
  cursor: pointer;
  line-height: 32px;
  font-size: 12px;
  color: #909399;
}
/* 更改图标样式 */
.home_content {
  .el-tabs--card > .el-tabs__header .el-tabs__item .el-icon-close {
    width: 16px;
    height: 16px;
    background-color: #969799;
    color: #ffffff;
  }
  .el-tabs--card
    > .el-tabs__header
    .el-tabs__item.is-active.is-closable
    .el-icon-close {
    background-color: #fff;
    color: $bg_color;
    width: 16px;
    height: 16px;
  }
  .el-tabs--card
    > .el-tabs__header
    .el-tabs__item.is-closable:hover
    .el-icon-close {
    width: 16px;
    height: 16px;
  }
  .el-tabs--card
    > .el-tabs__header
    .el-tabs__item.is-active.is-closable
    .el-icon-close:hover {
    background-color: #cf5351;
    color: #ffffff;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__item .el-icon-close:hover {
    background-color: #cf5351;
  }
}
.home_content {
  /* 更改tabs属性 */
  .el-tabs--card > .el-tabs__header {
    user-select: none;
    background: #ffffff;
    box-shadow: 0px 0px 6px rgba(0, 167, 84, 0.12);
    padding: 0 10px;
    margin: 0 0 5px;
  }
  .el-tabs__nav-wrap {
    padding: 8px 20px 0 20px;
    .el-tabs__nav-prev,
    .el-tabs__nav-next {
      font-size: $font_size;
    }
    .el-tabs__nav {
      border: 0;
      .el-tabs__item {
        border-top-right-radius: 4px;
        border-top-left-radius: 4px;
        font-weight: 400;
        border: 0;
        font-size: $font_size;
        margin-left: 4px;
        background: #f1f1f5;
        line-height: 32px;
        height: 32px;
      }
      // .el-tabs__item:not(.is-active):focus,.el-tabs__item:not(.is-active):active,
      // .el-tabs__item:not(.is-active):visited{
      // padding-left: 20px;
      // padding-right: 20px;
      // background: linear-gradient(to bottom, #d4cdc3 -10px, $bg_color 10px);
      // color: #FFFFFF;
      // }
      .el-tabs__item:not(.is-active):hover {
        padding-left: 20px;
        padding-right: 20px;
        background: $bg_colorTable;
        color: rgba(0, 0, 0, 0.5);
      }
      .el-tabs__item:first-child {
        margin-left: 0px;
      }
      .is-active {
        color: #ffffff;
        // background: linear-gradient(
        //   to bottom,
        //   #d4cdc3 -10px,
        //   $bg_background1 10px
        // );
        background: linear-gradient(
          to bottom,
          $bg_background2,
          $bg_background1
        );
      }
    }
  }
}
</style>
<style lang="scss" scoped>
/**添加鼠标右键*/
.tags {
  position: relative;
}
.contextmenu {
  font-size: 12px;
  color: #909399;
  position: absolute;
  margin: 0;
  padding: 5px 0;
  background: #fff;
  z-index: 1000;
  list-style-type: none;
  border-radius: 4px;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.1);
  li {
    margin: 0;
    padding: 5px 15px;
    cursor: pointer;
    &:hover {
      background: #eee;
    }
  }
}
.left_nav_div {
  position: absolute;
  width: auto;
  height: calc(100% - 55px);
  bottom: 0;
  overflow: hidden;
  padding: 0 12px 14px $px_24;
  > div {
    width: auto;
    height: 100%;
    overflow: scroll;
    //box-shadow: 0px 0px 6px rgba(0, 167, 84, 0.12);
  }
  > div {
    scrollbar-width: none;
    -ms-overflow-style: none;
  }
  > div::-webkit-scrollbar {
    display: none;
  }
}
.title:hover {
  cursor: pointer;
}
.nav_home_I {
  padding-left: 5px;
}
.nav_home_I:hover {
  color: $bg_color;
}
</style>
